package com.dmall.search.service.impl;

import com.dmall.framework.result.DmallResult;
import com.dmall.manager.model.ItemModel;
import com.dmall.manager.service.ItemService;
import com.dmall.search.service.SearchItemService;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 索引库维护Service
 * @author Chen 2017/10/25
 */
@Service
public class SearchItemServiceImpl implements SearchItemService {
    @Autowired
    private ItemService itemService;
    @Autowired
    private SolrServer solrServer;
    /**
     *  导入所有商品信息
     * @return
     */
    @Override
    public DmallResult importAllItems() {
        try {
            List<ItemModel> itemList = itemService.getItemList();
            for(ItemModel searchItem : itemList){
                //创建文档对象
                SolrInputDocument document = new SolrInputDocument();
                document.addField("id",searchItem.getId());
                document.addField("item_title",searchItem.getTitle());
                document.addField("item_sell_point",searchItem.getSell_point());
                document.addField("item_image",searchItem.getImage());
                document.addField("item_category_name",searchItem.getCategory_name());
                document.addField("item_price",searchItem.getPrice());
                solrServer.add(document);
            }
            solrServer.commit();
            return DmallResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return DmallResult.build(500,"数据导入时发生异常");
        }
    }
}
